<?php
namespace Admin\Widget;
use Think\Controller;

class MenuWidget extends Controller {

	/**
	 * [leftMenu 返回左侧菜单]
	 * @return [string] [左侧菜单HTML结构]
	 */
	public function leftMenu() {
		$return_str = '';

		$menuObj = D('Menu');
		$rel = session('perm');
		foreach ($rel as $k=>$v){
			if($rel[$k]['show']==0){
				unset($rel[$k]);
			}
		}
		$menuArr = $menuObj->getTree($rel);
        foreach ($menuArr as $key => $value) {
              $menu = $value->menu;
              $return_str .= $this->generateHTML($value);
        }
		echo $return_str;
	}

	private function generateHTML( $value ){
		$str =  '<li>';

		$menu = $value->menu;
		$url = "#";

		$title = $menu['name'];
		 //解析语言包
		if( preg_match('/L\(.+?\)/', $title) ) {
			eval('$title = '.$title.";" );
		}else{
			//判断系统选定语言
			if( I('cookie.think_language')=='en-us' ) {
				$title = $menu['en_name'];
			}
		}
		$target = '';
		if( $menu['url'] ){
			$url = $menu['url'];
			$target = ' target="_blank" ';
		}elseif( $menu['module'] && $menu['controller'] && $menu['action'] ){
			//支持action以后的参数
			if($menu['param'])
			{
				$url = U( $menu['module'] .'/'. $menu['controller'] .'/'. $menu['action'] , $menu['param']);
			}else{
				$url = U( $menu['module'] .'/'. $menu['controller'] .'/'. $menu['action'] );
			}
		}

		$str .='<a href="'. $url .'" title="'.$title.'" '.$target.'>';

		if( $menu['icon'] ){
			$str .= '<i class="fa fa-lg fa-fw '.$menu['icon'].'"></i>';
		}

		$close_span = '';
		if( $menu['pid'] ==0 )
		{
			$close_span = '</span>';
			$str .= '<span class="menu-item-parent">';
		}

		$str .= $title.$close_span.'</a>';

		if( $value->nodes ){
			$str .= "<ul>";
			foreach($value->nodes as $v  ){
			$str .= $this->generateHTML($v);
			}
			$str .= "</ul>";
		}
		$str .= "</li>";

		return $str;
	}
}